package com.accp.utils;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

	private static SqlSessionFactory factory;
	
	static{
		//初始化SqlSessionFactory
		try{
			//读取配置文件
			InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
			//构建session工厂
			factory = new SqlSessionFactoryBuilder().build(is);
		}catch(Exception ex){
			throw new RuntimeException("初始化失败",ex);
		}
	}
	
	public static SqlSession createSqlSession(){
		return factory.openSession(false);
	}
	
	public static SqlSession createSqlSession(boolean autoCommit){
		return factory.openSession(autoCommit);
	}
	
	public static void closeSqlSession(SqlSession session){
		if(session != null){
			session.close();
		}
	}
}
